#include "utils/init.h"
#include "utils/glutil.h"
#include "utils/logger.h"
#include <psp2/kernel/threadmgr.h>

#include <falso_jni/FalsoJNI.h>
#include <so_util/so_util.h>
#include "reimpl/controls.h"
#include <stdio.h>
int _newlib_heap_size_user = 256 * 1024 * 1024;

#ifdef USE_SCELIBC_IO
int sceLibcHeapSize = 4 * 1024 * 1024;
#endif
#define SCREEN_W 960
#define SCREEN_H 544
//#define SCREEN_H 640
so_module so_mod;

jobjectArray JobjectArray;
int StartOffset;
char* dspUserID;

int main_thread(SceSize args, void *argp)
{
    debugPrintf("RenderUpdate strart \n");
	int (* NativeFrame)(void) = (void *)so_symbol(&so_mod, "Java_com_gamevil_nexus2_Natives_NativeRender");
    int (* handleCletEvent)(int,int,int,int,int) = (void *)so_symbol(&so_mod, "Java_com_gamevil_nexus2_Natives_handleCletEvent");
    
    int index=0;
    int fpsLock=24;
    uint32_t last_render_time = sceKernelGetProcessTimeLow();
        uint32_t delta = (1000000 / (fpsLock+1));

        while (1) {
            //controls_poll();
            NativeFrame();

            while (sceKernelGetProcessTimeLow() - last_render_time < delta) {
                sched_yield();
            }
            if(index>2)
            {
                if(index<=3)
                {
                   handleCletEvent(0,0,2,-16,0);
                   handleCletEvent(0,0,3,-16,0);
                   debugPrintf("handleCletEvent over \n");
                   index++;
                }
            }
            else
            {
               index++;
            }
            

            last_render_time = sceKernelGetProcessTimeLow();

			 gl_swap();
        }
    debugPrintf("RenderUpdate over \n");
	return 0;
}

int main() {
    soloader_init_all();

    int (* JNI_OnLoad)(void *jvm,int) = (void *)so_symbol(&so_mod, "JNI_OnLoad");
    JNI_OnLoad(&jvm,0);
    chdir(DATA_PATH);
    gl_init();
    int (* OnNativeInitializeJNI)(void *) = (void *)so_symbol(&so_mod, "Java_com_gamevil_nexus2_Natives_InitializeJNIGlobalRef");
    int (* NativeInitialize)() = (void *)so_symbol(&so_mod, "Java_com_gamevil_nexus2_Natives_NativeInit");
    int (* NativeSize)(int,int,int,int) = (void *)so_symbol(&so_mod, "Java_com_gamevil_nexus2_Natives_NativeResize");
    int (* NativeIsNexusOne)(int,int,int) = (void *)so_symbol(&so_mod, "Java_com_gamevil_nexus2_Natives_NativeIsNexusOne");
    
    OnNativeInitializeJNI(&jni);
    debugPrintf("OnNativeInitializeJNI over \n");

    NativeIsNexusOne(0,0,0);
    debugPrintf("NativeIsNexusOne over \n");

    NativeInitialize();
    debugPrintf("NativeInitialize over \n");

    NativeSize(0,0,SCREEN_W,SCREEN_H);
    debugPrintf("NativeSize over \n");

    //eglSwapInterval(0, 2);

    // ... do some initialization

    SceUID thid = sceKernelCreateThread("main_thread", (SceKernelThreadEntry)main_thread, 0x40,2* 128 * 1024, 0, 0, NULL);
	sceKernelStartThread(thid, 0, NULL);
	return sceKernelExitDeleteThread(0);
}
